package com.kaifamiao.base.Demo20210923;


/**
 * @author lucien-ma
 * @date 2021/9/23
 * @apiNote
 */
public class Demo01 {

    public static void main(String[] args) {
        String str = "0000 0000 0000 0000 0000 0000 0000 1000"; // 8
        String str2 = "1111 1111 1111 1111 1111 1111 1111 1000";// -8
        //System.out.println(str);
        //System.out.println(str.replaceAll("[\\s]+",""));
        int dec = toDec(str2.replaceAll("[\\s]+", ""));
        System.out.println(dec);

    }

    public static int toDec(String str) {
        // 先将其变成一个数组
        int[] strBrinay = new int[32];
        for (int i = str.length() - 1; i >= 0; i--) {
            strBrinay[i] = Integer.parseInt(String.valueOf(str.charAt(i)));
        }
        // 先取出符号位，如果是负数则先计算出原码
        int symbol = strBrinay[0];
        if (symbol == 1) {
            // 计算出原码
            strBrinay = getSourceCode(strBrinay);
        }
        int dec = 0;
        int pow = 0;
        for (int i = strBrinay.length - 1; i >= 1; i--) {
            dec += strBrinay[i] * Math.pow(2, pow++);
        }
        return symbol == 0 ? dec : -dec;
    }

    /**
     * 求出负数的原码
     * @param str
     * @return
     */
    private static int[] getSourceCode(int[] str) {
        // 补码减一
        for (int i = str.length - 1; i >= 1; i--) {
            if (str[i] == 1) {
                str[i] = 0;
                break;
            } else if (str[i] == 0) {
                str[i] = 1;
            }
        }
        // 取反
        for (int i = 1; i < str.length; i++) {
            if (str[i] == 0) {
                str[i] = 1;
            } else {
                str[i] = 0;
            }
        }
        return str;
    }
}
